import {forEach, isEmpty, isObject} from "lodash-es";

let ins = null;

class FinderCache {

    /**
     * 查找器的配置缓存。以 finderCode 为 key
     * @type {{}}
     */
    confCaches = {};

    constructor() {

        if (isEmpty(!ins)) {
            return ins;
        }

        ins = this;
    }

    addConfCache(key, value) {
        this.confCaches[key] = value;
    }

    getConfCache(key) {
        return this.confCaches[key] || {};
    }

    deleteConfCache(key) {
        delete this.confCaches[key];
    }

    resetConfCache(values = {}) {
        this.confCaches = values;
    }

    loading = {};

    /**
     * 正在获取枚举数据的 枚举组件的实例。
     * 以 finderCode 为 key，以 {[FinderSelect实例的唯一标识]: FinderSelect实例} 为 value。
     * 用于在获取枚举数据之后，统一更新这些枚举组件
     * @type {{}}
     */
    loadingInstances = {};

    addLoadingIns(code, insKey, ins) {
        if (!isObject(this.loadingInstances[code])) {
            this.loadingInstances[code] = {};
        }
        this.loadingInstances[code][insKey] = ins;
    }

    removeLoadingIns(code, insKey) {
        if(this.loadingInstances[code]) {
            delete this.loadingInstances[code][insKey];
        }
    }

    updateInstances(code) {
        // console.log('updateInstances', this.loadingInstances);
        forEach(this.loadingInstances[code], (ins) => {

            if (ins && ins.setPropsByConf) {
                ins.finderConf = this.getConfCache(code);
                ins.setPropsByConf();
            }
        });
        delete this.loadingInstances[code];
    }

}

export default new FinderCache();
